const express = require("express");
const app = express();

// 不做任何限定的中间件
/* app.use((req, res, next) => {
  console.log("Time:", Date.now());
  next();
}); */

// 限定请求路径的中间件
/* app.use("/user/:id", (req, res, next) => {
  console.log("Request Type:", req.method);
  next();
}); */

// 限定请求方法 + 请求路径
app.get("/", (req, res) => {
  res.send("Hello World");
});

// 多个处理函数
/* app.use(
  "/user/:id",
  (req, res, next) => {
    console.log("Request URL:", req.originalUrl);
    next();
  },
  (req, res, next) => {
    console.log("Request Type:", req.method);
    next();
  }
);

app.get("/user/:id", (req, res) => {
  res.send("user/:id");
}); */

// 为同一个路径定义多个处理中间件
/* app.get(
  "/user/:id",
  (req, res, next) => {
    console.log("ID:", req.params.id);
    next();
  },
  (req, res, next) => {
    res.send("User Info");
    next()
  }
);

app.get("/user/:id", (req, res, next) => {
  // 同一个请求只能有一个响应
  res.end(req.params.id);
}); */

// 跳过中间件
/* app.get(
  "/user/:id",
  (req, res, next) => {
    if (req.params.id === "0") next("route");
    else next();
  },
  (req, res, next) => {
    res.send("regular");
  }
);

app.get("/user/:id", (req, res, next) => {
  res.send("special");
}); */

// 中间件数组(路由中间件)
function logOriginalUrl(req, res, next) {
  console.log("Request URL:", req.originalUrl);
  next();
}

function logMethod(req, res, next) {
  console.log("Request Method:", req.method);
  next();
}

let logStuff = [logOriginalUrl, logMethod];
app.get("/user/:id", logStuff, (req, res, next) => {
  res.send("User Info");
});

app.listen(3000, () => {
  console.log("server is running at http://localhost:3000");
});
